package com.example.webviewdemo.slice;

import com.example.webviewdemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.webengine.*;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.PixelMap;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Delayed;

public class MainAbilitySlice extends AbilitySlice {
    WebView webView;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        // 获取WebView组件
        webView = (WebView) findComponentById(ResourceTable.Id_webview);
        // 设置自定义的webAgent代理
        webView.setWebAgent(new WebAgent(){
            // 覆写此方法来设置是否需要加载某url
            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                return true;
            }
            // 此方法在内容加载时会调用
            @Override
            public void onLoadingContent(WebView webView, String url) {
                super.onLoadingContent(webView, url);
            }
            // 此方法在页面加载完成时会调用
            @Override
            public void onPageLoaded(WebView webView, String url) {
                super.onPageLoaded(webView, url);
            }
            // 此方法在页面加载时会调用
            @Override
            public void onLoadingPage(WebView webView, String url, PixelMap icon) {
                super.onLoadingPage(webView, url, icon);
            }
            // 此方法在发生异常时会调用
            @Override
            public void onError(WebView webView, ResourceRequest request, ResourceError error) {
                super.onError(webView, request, error);
            }
        });
        // 加载百度首页
        webView.load("https://www.baidu.com");

        // 获取导航器实例对象
        Navigator navigator = webView.getNavigator();

        // 获取WebView配置对象
        WebConfig config = webView.getWebConfig();
        // 开启JavaScript脚本支持
        config.setJavaScriptPermit(true);

        // 异步延迟执行
        getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                // Native调用JS
                webView.executeJs("document.nodeName", new AsyncCallback<String>() {
                    @Override
                    public void onReceive(String s) {
                        // 调用结果的回调
                        HiLog.info(new HiLogLabel(0,0,"webView"),s);
                    }
                });
            }
        },10000);

        webView.addJsCallback("JSCallNativeName", new JsCallback() {
            @Override
            public String onCallback(String s) {
                // 此处写原生端逻辑
                return null;
            }
        });

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);

    }
}
